<template>
  <div>
    <NuxtLayout name="default">
      <template #mainLeft>
        <div class="back" @click="back">
          <Icon name="el-icon-ArrowLeft"/>
          返回创作大厅
        </div>

        <div
            class="h-full w-[400px] flex flex-col bg-white"
            style="border-radius: 15px 0 0 15px"
        >
          <div style="padding: 10px">
            <el-tag type="warning" v-for="(item,index) in modelData.multiple_model" :key="index" style="margin-right: 15px;cursor: pointer;margin-bottom: 5px;border: 1px solid #784c2c"
                    @click="tizozhuan(item.model_id)">{{item.model_name}}</el-tag>
          </div>
          <div class="flex p-[20px]">


            <div class="text-lg font-medium line-clamp-1 mr-auto">
              {{ modelData.name }}
            </div>
           <!-- <ElButton link type="primary" @click="insertExample"
            >插入示例
            </ElButton
            >-->
          </div>
          <div class="flex-1 min-h-0">
            <ElScrollbar>
              <div class="p-[20px]">
                <FormDesigner
                    ref="formDesignerRef"
                    v-model="formData"
                    :form-lists="modelData.form"
                    :model_id="modelData.id"
                    size="large"
                    @img="imgStatus"
                    @img_generation="imggenerationStatus"
                    @file="fileStatus"
                    @form="formStatus"
                    @videoStatus="videoStatus"
                    @videomp3Status="videomp3Status"
                />
              </div>
            </ElScrollbar>
          </div>

          <div class="px-[20px] pb-[20px]">
            <!--模型选择-->
            <ModelPicker style="display: none"
                 :is-create="true"
                 v-model="chatModel"
                 v-model:model="chatModelConfig"
             ></ModelPicker>
            <!--立即生成-->

            <div class="flex flex-col justify-center items-center" v-if="modelData.is_open_batch == 0">
              <ElButton v-if="is_img&&is_form&&is_file&&is_videomp3&&is_video&&is_img_gen&&is_video_url"
                  class="create-btn"
                  @click="handleCreate"
                  :loading="isReceiving"
                  type="primary"
              >
                智能创作
              </ElButton>
              <ElButton v-else
                        class="create-btn"
                        :loading="true"
                        type="primary"
              >
                {{ is_video_url == 0 ? '链接解析中...' : '文件上传中...' }}
              </ElButton>
            </div>

            <div class="flex flex-col justify-center items-center" v-if="modelData.is_open_batch == 1">

              <ElButton v-if="is_img&&is_form&&is_file&&is_videomp3&&is_video&&is_img_gen&&!is_submit"
                        class="create-btn"
                        @click="handleCreateBath"
                        :loading="isReceiving"
                        type="primary"
              >
                提交

              </ElButton>
              <ElButton v-else-if="is_submit"
                        class="create-btn"
                        :loading="true"
                        type="primary"
              >
                任务提交中...
                <!-- <span v-html="getCountMsg" class="text-xs ml-2"/>-->
              </ElButton>
           
              <ElButton v-else
                        class="create-btn"
                        :loading="true"
                        type="primary"
              >
                文件上传中...
                <!-- <span v-html="getCountMsg" class="text-xs ml-2"/>-->
              </ElButton>

            </div>

          </div>
        </div>
      </template>
      <div class="h-full flex">
        <div data-v-69cc7360="" class="ai-chat-header">

          <div data-v-69cc7360="" class="ai-chat-header-left">
            <div data-v-69cc7360="" class="ai-avatar">
              <div data-v-12bde410="" data-v-69cc7360="" class="image fill" alt="" >
                <img data-v-12bde410="" loading="lazy" :src="modelData.image" style="object-fit: cover;border: 3px solid rgb(235, 205, 119);border-radius: 50%" v-if="userStore.userInfo.is_member&&userStore.userInfo.member_expired == 0">
                <img data-v-12bde410="" loading="lazy" :src="modelData.image" style="object-fit: cover;" v-else>
              </div>
            </div>
            <div data-v-69cc7360="" class="ai-name">
              {{ modelData.name }}
            </div>

            <div v-if="userStore.isLogin">
              <div data-v-69cc7360="" class="flex-center" v-if="modelData.balance == 0">
                <div data-v-69cc7360="" class="ai_free ai_useType" v-if="!(userStore.userInfo.is_member&&userStore.userInfo.member_expired == 0)">限免</div>
                <div data-v-69cc7360="" class="ai_freev1 ai_useType" v-else>
                  <img data-v-3b606504="" src="https://www.caixue8.cn/uploads/wap/f-vip_1.png" alt="" class="ic_coin">
                  <text>限免</text>
                </div>
              </div>
               <div v-else>
                 <div data-v-69cc7360="" class="invite-btn" v-if="!(userStore.userInfo.is_member&&userStore.userInfo.member_expired == 0)">
                   <img data-v-69cc7360="" src="https://www.caixue8.cn/uploads/wap/T-32.png" alt="" class="ic_coin">
                   <span data-v-69cc7360="">{{ modelData.balance }}</span>
                 </div>
                 <div data-v-69cc7360="" class="invite-btnv1" v-else>
                   <img data-v-69cc7360="" src="https://www.caixue8.cn/uploads/wap/f-vip_1.png" alt="" class="ic_coin">
                   <span data-v-69cc7360="">{{ modelData.balance }}</span>
                 </div>
               </div>
            </div>
          </div>
        </div>
        <ChattingChattingv1
            ref="chattingRef"
            v-model:model="chatParams.model"
            v-model:network="chatParams.network"
            v-model:plugin="plugins"
            :content-list="chatContentList"
            :send-disabled="isReceiving"
            :selectval="sessionActive"
            :avatar="modelData.image"
            :model_name="modelData.name"
            :model_id="modelData.id"
            :is_member_download="modelData.is_member_download"
            :is_open_batch="modelData.is_open_batch"
            :is_submit="is_submit"
            :currentId="currentId"
            :sendDisabled="sendDisabled"
            :chat-type="1"
            @close="chatClose"
            @content-post="contentPost"
            @clean-chat-log="cleanChatLog"
            @qingkong="qingkong"
            @top="handleTop"
            @addMsg="addMsg"
            @plMsg="plMsg"
            @addFrom="addFrom"
        >
          <div
              v-show="hasMoreDialogueRecords && userStore.isLogin"
              class="h-[40px] py-[10px] text-[#999] text-center cursor-pointer"
              @click.stop="handleTop"
          >
            <template
                v-if="hasMoreDialogueRecords && userStore.isLogin"
            >
              {{
                dialogueRecordsLoading
                    ? '正在加载中...'
                    : '-- 点击加载 --'
              }}
            </template>
          </div>
          <div class="px-[50px]">
            <div data-v-fc8ab866="" class="chat-item">
              <div data-v-fc8ab866="" class="ai-avatar">
                <div data-v-12bde410="" data-v-fc8ab866="" class="image fill" alt="">

                  <div v-if="userStore.userInfo.is_member == 1&&userStore.userInfo.member_expired == 0" style="position: relative">

                    <img data-v-12bde410="" loading="lazy"
                         :src="modelData.image"
                         style="object-fit: cover;border: 3px solid rgb(235, 205, 119);border-radius: 50%">
                  </div>
                  <div v-else>
                    <img data-v-12bde410="" loading="lazy"
                         :src="modelData.image"
                         style="object-fit: cover;">
                  </div>
                </div>
              </div>
              <div data-v-fc8ab866="" class="not-chat-content">
                <div data-v-fc8ab866="" class="welcome-content">
                  <div data-v-fc8ab866="" class="welcome-name">欢迎使用 {{modelData.name}}</div>
                  <div data-v-fc8ab866="" v-html="modelData.copywriting"></div>
                </div>
              </div>
            </div>
          </div>
        </ChattingChattingv1>

        <el-dialog v-model="dialogTableVisible" title="历史记录" width="800">
          <TheSessionv1 @updateHide="updateHide"/>
        </el-dialog>


        <el-dialog v-model="dialogTableVisiblepl" title="任务记录" width="800" @close="updateHidepl">
          <TheSessionv2  :itemData="plLists" :options="optionsLists" @words="words" @wordsAll="wordsall" @updateHideList="updateHideList" @updateHide="editshow"/>
        </el-dialog>

        <el-dialog
            v-model="dialogVisibleVip"
            title="提示"
            width="500"
            :before-close="handleClose"
        >
          <span>您使用了会员功能，请先成为会员</span>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogVisibleVip = false">在看看</el-button>
              <el-button type="primary" @click="addVip">
                开通会员
              </el-button>
            </div>
          </template>
        </el-dialog>
      </div>
      <TheGuidedPopup ref="guidedPopupRef"/>
    </NuxtLayout>



  </div>
</template>
<script setup lang="ts">

import {
  getchatLog,
  samplesLists,
  cleanChat,
  chatSendText,
  getCheck,
  getUserCheck,
  chatSendTextv1,
  getChatCategoryListspl, getChatListsplKeyList, getScanFile, videoTransform
} from '@/api/chat'
import {useUserStore} from '~~/stores/user'
import feedback from '~~/utils/feedback'
import {ElAvatar, ElButton, ElMessageBox, ElScrollbar} from 'element-plus'
import {useAppStore} from '~/stores/app'
import {isNewDay} from '~/utils/validate'
const dialogVisibleVip = ref(false)
const formData = ref<any>({})
import {CHAT_LIMIT_KEY, CHAT_MODEL_KEY, PLUGIN_MODEL_KEY} from '~/enums/cacheEnums'
import {watch} from 'vue'
const is_vip = ref<any>({})
const formDesignerRef = shallowRef()
import TheSessionv1 from '@/components/the-session/indexv1.vue'
import TheSessionv2 from '@/components/the-session/indexv2.vue'
import ModelPicker from "~/components/chatting/model-picker.vue";
import {getCreationDetail} from "~/api/create";
import {cloneDeep} from "lodash-es";
import {img_understand} from "~/components/form-designer/widgets";
import _MessageBox from "element-plus/es/components/message-box";
import {downloadV1, downloadWords, downloadWordsAll} from "~/api/my";
import {pptUse} from "~/api/user";

const userStore = useUserStore()
const appStore = useAppStore()
const router = useRouter()
const route = useRoute()
const currentId = ref(Number(route.query.id))
const cate_id = ref(Number(route.query.cate_id))
const is_img = ref(1)
const is_img_gen = ref(1)
const is_file = ref(1)
const is_form = ref(1)
const is_video = ref(1)
const is_videomp3 = ref(1)
const is_video_url = ref(1)
const batch_key = ref('')
const plLists = ref([])
const optionsLists = ref([])

if(currentId.value > 0) {
  window.localStorage.setItem('other_id',currentId.value)
}
const scrollbarRef = ref<InstanceType<typeof ElScrollbar>>(null)
const currentCreationHistory = ref<any[]>([])
//对话记录列表
const dialogTableVisible = ref(false)
const dialogTableVisiblepl = ref(false)
//对话记录列表
const isFrom = ref(true)

const sendDisabled = ref(false)
const handleClose = (done: () => void) => {
  console.log('关闭')
}

const is_submit = ref(false)

const addVip = () => {
  router.push('/openvip');
}
//对话框ref
const chattingRef = ref(null)
const guidedPopupRef = shallowRef()
// 聊天次数(消耗
const chatModelConfig = ref({
  balance: 1,
  member_free: false
})
const chatModel = ref<string>('')
const chatParams = reactive({
  model: '',
  network: false
})

const plugins = reactive({
  type: '',
  id: '',
  file: {} as any
})

const updateHide = (value) => {
  //sessionActive.value = value
  chatLogParams.category_id = value
  getChatList()
  dialogTableVisible.value = false
}


const updateHidepl = (value) => {
  console.log('执行了吗')
  dialogTableVisiblepl.value = false
  stopPolling()
}

const tizozhuan = (id) => {
      router.push({
        path: '/create/produce',
        query: {
          id
        }
      })
  currentId.value = id
  modelApiRefresh();
  getChatList()
}

const pl_none = ref([])

const insertExample = () => {
  modelData.value?.form.forEach((item: any) => {
    if (item.props.placeholder && !item.props.defaultValue) {

      formData.value[item.id] = item.props.placeholder
    }
  })
}

const strmx = ref<any>({})
const setFormDataDefault = () => {
  modelData.value?.form.forEach((item: any) => {
    if (item.props.defaultValue) {
      formData.value[item.id] = cloneDeep(item.props.defaultValue)
    } else {
      formData.value[item.id] = undefined
    }
  })
}

const imgStatus = (e) => {
   is_img.value = e
}

const imggenerationStatus = (e) => {
  is_img_gen.value = e
}

const fileStatus = (e) => {
  is_file.value = e
}

const formStatus = (e) => {
  is_form.value = e
}

const videoStatus = (e) => {
  is_video.value = e
}
const videomp3Status = (e) => {
  is_videomp3.value = e
}
const back = () => {
  router.push('/create')
}


const updateHideList = async (e) => {
  let key = e.value
  batch_key.value = key
  lungetList()
}

const editshow = async (value) => {
  chatLogParams.page_no = 1
  chatContentList.value = []
  chatLogParams.category_id = value
  getChatList()
  dialogTableVisiblepl.value = false
}

const getCountMsg = computed(() => {
  if (!chatModelConfig.value.key) return ''
  if (!chatModelConfig.value.member_free) {
    if (chatModelConfig.value.balance) {
      return '';//`消耗 ${chatModelConfig.value.balance} T币`
    } else {
      return '免费'
    }
  } else {
    return '会员免费'
  }
})

const resetPluginData = () => {
  plugins.file = {url: ''}
}


const handleCreateBath = async() => {
  if(sendDisabled.value){
    return false;
  }
  try {
    await formDesignerRef.value?.validate()
  } catch (error) {
    feedback.msgError('必填项不能为空')
    return
  }

  if (userStore.userInfo.is_chat_limit && isNewDay(true, CHAT_LIMIT_KEY)) {
    try {
      await ElMessageBox.confirm(
          '已超过会员对话上限次数，继续对话将会消耗账户的对话余额',
          '对话上限提示',
          {
            showClose: false,
            confirmButtonText: '继续',
            cancelButtonText: '关闭'
          }
      )
    } catch (e) {
      return
    }
  }

  // 保存聊天模型（用于刷新之后还能记住当前聊天模型
  const model = useCookie(CHAT_MODEL_KEY)
  model.value = chatModel.value
  pl_none.value = []

  let str = ''
  for (const key in modelData.value.form) {
    let id = modelData.value.form[key].id
    let value = formData.value[id] ? formData.value[id] : ''
    if(modelData.value.form[key].props.isPl){
      pl_none.value.push(id)
    }
    if(userStore.userInfo.is_member == 1 && userStore.userInfo.member_expired == 0) {
    }else{

      if (modelData.value.form[key].props.isMemberUse!=false) {
        console.log(modelData.value.form[key].props.isMemberUse)
        if (value) {
          await ElMessageBox.confirm(
              '您使用了 【' + modelData.value.form[key].props.title + '】 会员专用功能，当前未开通会员',
              '对话提示',
              {
                showClose: false,
                confirmButtonText: '去开通',
                cancelButtonText: '关闭'
              }
          ).then(() => {
            // 用户点击确认，执行页面跳转
            router.push('/openvip');
          }).catch(() => {
            // 用户点击取消，执行其他逻辑（如果有需要）
          });
          return false;
        }
      }
    }

    /*if(id!='img_generation'&&id!='img_up' && id !='file_up' && id !='form_up' && id !='img_understand' && id !='video_understand'&& id !='transcription_up'){
      str += `${modelData.value.form[key].props.title}:${value} `
    }else {
      if (value && (id == 'img_generation' || id == 'img_up' || id == 'file_up' || id == 'form_up' || id == 'img_understand' || id == 'video_understand'|| id == 'transcription_up')) {
        let img = '';
        for (const key1 in value){
          img += (key1>0?',':'') + value[key1].name
        }
        str += `${modelData.value.form[key].props.title}:${img} `
      }
    }*/


    // 定义动态正则表达式：匹配基础ID + 数字后缀（或无后缀）
    const SPECIAL_IDS_REGEX = /^(img_generation|form_up|img_understand|video_understand|transcription_up|img_up\d*|file_up\d*)$/;

    if (value) { // 统一前置空值校验
      // 判断是否为特殊字段（正则匹配）
      const isSpecialField = SPECIAL_IDS_REGEX.test(id);

      if (!isSpecialField) {
           // 普通字段：直接拼接值
          str += `${modelData.value.form[key].props.title}:${value} `;
      } else {
          // 特殊字段：处理文件名集合
          const fileNames = [];

          // 兼容两种数据结构：数组或对象
          if (Array.isArray(value)) {
            fileNames.push(...value.map(item => item?.name || ''));
          } else if (typeof value === 'object') {
            fileNames.push(...Object.values(value).map(item => item?.name || ''));
          }

          // 过滤空值并拼接
          const validNames = fileNames.filter(name => name.trim());
          if (validNames.length > 0) {
            str += `${modelData.value.form[key].props.title}:${validNames.join(', ')} `;
          }
      }
    }
    console.log(value)
    console.log(str)
    console.log('打印出来看看是啥呀')
  }
  isFrom.value = false
  contentPostv1(formData.value, 0, str)
}

const handleCreate = async () => {
  if(sendDisabled.value){
    return false;
  }
  try {
    await formDesignerRef.value?.validate()
  } catch (error) {
    feedback.msgError('必填项不能为空')
    return
  }







  if (userStore.userInfo.is_chat_limit && isNewDay(true, CHAT_LIMIT_KEY)) {
    try {
      await ElMessageBox.confirm(
          '已超过会员对话上限次数，继续对话将会消耗账户的对话余额',
          '对话上限提示',
          {
            showClose: false,
            confirmButtonText: '继续',
            cancelButtonText: '关闭'
          }
      )
    } catch (e) {
      return
    }
  }

  // 保存聊天模型（用于刷新之后还能记住当前聊天模型
  const model = useCookie(CHAT_MODEL_KEY)
  model.value = chatModel.value

  let str = ''
  let input_video_url = false
  for (const key in modelData.value.form) {
    let id = modelData.value.form[key].id
    if(id == 'input_video_url'){
      input_video_url = true
    }
    let value = formData.value[id] ? formData.value[id] : ''
    if(userStore.userInfo.is_member == 1 && userStore.userInfo.member_expired == 0) {
    }else{

      if (modelData.value.form[key].props.isMemberUse!=false) {
        console.log(modelData.value.form[key].props.isMemberUse)
        if (value) {
          await ElMessageBox.confirm(
              '您使用了 【' + modelData.value.form[key].props.title + '】 会员专用功能，当前未开通会员',
              '对话提示',
              {
                showClose: false,
                confirmButtonText: '去开通',
                cancelButtonText: '关闭'
              }
          ).then(() => {
            // 用户点击确认，执行页面跳转
            router.push('/openvip');
          }).catch(() => {
            // 用户点击取消，执行其他逻辑（如果有需要）
          });
          return false;
        }
      }
    }

    /*if(id!='img_generation'&&id!='img_up' && id !='file_up' && id !='form_up' && id !='img_understand' && id !='video_understand'&& id !='transcription_up'){
      str += `${modelData.value.form[key].props.title}:${value} `
    }else {
      if (value && (id == 'img_generation' || id == 'img_up' || id == 'file_up' || id == 'form_up' || id == 'img_understand' || id == 'video_understand'|| id == 'transcription_up')) {
         let img = '';
         for (const key1 in value){
              img += (key1>0?',':'') + value[key1].name
         }
         str += `${modelData.value.form[key].props.title}:${img} `
      }
    }*/

    // 定义动态正则表达式：匹配基础ID + 数字后缀（或无后缀）
const SPECIAL_IDS_REGEX = /^(img_generation\d*|form_up\d*|img_understand\d*|video_understand\d*|transcription_up\d*|img_up\d*|file_up\d*)$/;


if (value) { // 统一前置空值校验
  // 判断是否为特殊字段（正则匹配）
  const isSpecialField = SPECIAL_IDS_REGEX.test(id);

  if (!isSpecialField) {
    // 普通字段：直接拼接值
    str += `${modelData.value.form[key].props.title}:${value} `;
  } else {
    // 特殊字段：处理文件名集合
    const fileNames = [];
    console.log(value)
    // 兼容两种数据结构：数组或对象
    if (Array.isArray(value)) {
      console.log('执行了这里吗')
      fileNames.push(...value.map(item => item?.name || ''));
    } else if (typeof value === 'object') {
      console.log('还是执行了这里')
      fileNames.push(...Object.values(value).map(item => item?.name || ''));
    }

    if (fileNames.length > 0) {
      str += `${modelData.value.form[key].props.title}:${fileNames.join(', ')} `;
    }
  }
}

  }
  isFrom.value = false
  if(input_video_url){
      is_video_url.value = 0
      let input_video_file = formData.value.input_video_url
      if (!input_video_file.includes('https')) {
        is_video_url.value = 1
        ElMessage({
          showClose: true,
          message: '请输入有效的视频链接',
          type: 'error',
        })
        return false;
      }
      const is_ty = await isTbi(); // 顺序执行第二个验证
      console.log(is_ty)
      if(!is_ty){
          is_video_url.value = 1
          ElMessage({
            showClose: true,
            message: '已取消操作',
            type: 'error',
          })
          return;
      }
      let data = await videoTransform({
        link_url:input_video_file
      }).catch(err=>{
        is_video_url.value = 1
        return false;
      })
      if(!data) {
        console.log('执行了吗')
        is_video_url.value = 1
        return false;
      }
      formData.value.input_video_url = data.transcription_url
      
  }

  contentPost(formData.value, 0, str)
}

const {data: modelData, refresh: modelApiRefresh} = await useAsyncData(
    () =>
        getCreationDetail({
          id: currentId.value
        }),
    {
      default() {
        return {}
      },
      transform(data) {
        if (!data.form) {
            data.form = defaultForm
        }
        return data
      }
    }
)

watch(
    () => plugins.id,
    (val) => {
      if (val == 'gpt-4-all') {
        resetPluginData()
      }
    }
)
const {
  sessionActive,
  sessionAdd,
  currentSession,
  sessionEdit,
  getSessionLists
} = await useSessionList()

const getSessionListspl = async (batch_keys = '') => {
  if (!userStore.isLogin) return userStore.toggleShowLogin(true)
  if(!optionsLists.value.length) {
    const data1 = await getChatListsplKeyList({
      is_batch: 1,
      other_id: modelData.value.id
    });
    optionsLists.value = data1
    if (data1.length > 0) {
      batch_key.value = data1[0].batch_key
      const data = await getChatCategoryListspl({batch_key: batch_key.value, is_batch: 1})
      plLists.value = data.list
      for (let i = 0; i < data.list.length; i++) {
        if (data.list[i].batch_status != 2) {
          //触发轮询并跳出
          lungetList()
          break;
        }
      }
    }
  }
}



async function isTbi() {
  try {
    await ElMessageBox.confirm(
        '视频链接解析需要消耗T币',
        '提示',
        {
          showClose: false,
          confirmButtonText: '继续',
          cancelButtonText: '关闭'
        });

    return true;
  } catch (e) {
    return false;
  }
}


const lungetList = async () => {
  console.log('执行了吗11111')
  const data = await getChatCategoryListspl({batch_key: batch_key.value,is_batch:1})
  plLists.value = data.list
  //判断是否需要执行轮询
  for(let i = 0;i < data.list.length;i++){

    if(data.list[i].batch_status!=2){
      //触发轮询并跳出
      setTimeout(function(){
        lungetList()
      },1000)
      break;
    }
  }
}

const addFrom = () => {
  isFrom.value = true
}


const words = (itemData) => {
  for (let i=0;i < itemData.length;i++){
    if(itemData[i].batch_status == 2) {
        piliang(itemData[i].id)
    }
  }
}


const wordsall = async (itemData) => {
  console.log('执行了吗')
  if (!((userStore.userInfo.is_member == 1 && userStore.userInfo.member_expired == 0) || modelData.is_member_download == 0)) {
    ElMessageBox.confirm(
        '会员专用功能，当前未开通会员',
        '对话提示',
        {
          showClose: false,
          confirmButtonText: '去开通',
          cancelButtonText: '关闭'
        }
    ).then(() => {
      // 用户点击确认，执行页面跳转
      router.push('/openvip');
    }).catch(() => {
      // 用户点击取消，执行其他逻辑（如果有需要）
    });
  }

  let data = await piliangAll(itemData)
  if(data.length > 0){
     let arrse = await downloadWordsAll({
        word_files:data.join(',')
     })

    window.location.href = 'https://www.caixue8.cn/api/chat_records/downloadV1?file_uri=' + arrse.file_uri

  }else{
    ElMessage({
      showClose: true,
      message: '下载失败',
      type: 'error',
    })
  }
}




const piliangAll = async (itemData) => {
  const promises = itemData.map(async (item) => {
    if (item.batch_status === 2) {
      const id = item.id;
      // 假设这段代码在浏览器环境中运行，因此可以使用document
      const element = document.getElementById('id_' + id);
      if (element) {
        const htmlContent = element.innerHTML;
        const str = htmlContent.replace(/uni-view/g, 'div');
        const res = await downloadWords({
          log_id: id,
          words: str,
          is_download: 0,
          is_batch: 1,
        });
        return res.file_uri;
      } else {
        console.error(`Element with id 'id_${id}' not found`);
        return null; // 或者抛出错误，取决于您的错误处理策略
      }
    } else {
      return null; // 对于batch_status不等于2的项，返回null或不处理
    }
  });

  try {
    const url_arr = await Promise.all(promises);
    // 过滤掉null值，如果需要的话
    const filteredUrlArr = url_arr.filter(Boolean);
    return filteredUrlArr;
  } catch (error) {
    console.error('Error processing items:', error);
    throw error; // 或者返回错误处理结果，取决于您的错误处理策略
  }
};


const piliang = (id) => {
  var element = document.getElementById('id_' + id);
  // 获取该元素的 HTML 内容
  var htmlContent = element.innerHTML;
  let str = htmlContent.replace(/uni-view/g, 'div')
  if ((userStore.userInfo.is_member == 1 && userStore.userInfo.member_expired == 0) || modelData.is_member_download == 0) {
    downloadWords({
      log_id: id,
      words: str,
      is_download: 0
    }).then((res) => {
      let arr = res.file_uri.split('/')
      let filename = arr[1]
      downloadFile(res.file_url,filename)
    })
  } else {
    ElMessageBox.confirm(
        '会员专用功能，当前未开通会员',
        '对话提示',
        {
          showClose: false,
          confirmButtonText: '去开通',
          cancelButtonText: '关闭'
        }
    ).then(() => {
      // 用户点击确认，执行页面跳转
      router.push('/openvip');
    }).catch(() => {
      // 用户点击取消，执行其他逻辑（如果有需要）
    });
  }
}


async function downloadFile(url, filename) {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`Failed to download ${filename}: ${response.statusText}`);
  }
  const blob = await response.blob();
  const urlObject = URL.createObjectURL(blob);
  const anchor = document.createElement('a');
  anchor.href = urlObject;
  anchor.download = filename;
  document.body.appendChild(anchor);
  anchor.click();
  document.body.removeChild(anchor);
  URL.revokeObjectURL(urlObject);
}



const addMsg = (index?: number) => {

  useAsyncData(() => getSessionLists(2, currentId.value), {
    default() {
      return []
    },
    immediate: true
  })
  setTimeout(function () {
    dialogTableVisible.value = true
  }, 300)

}


const plMsg = async(index?: number) => {
  await getSessionListspl(batch_key.value)
  setTimeout(function () {
    dialogTableVisiblepl.value = true
  }, 300)
}

const arocde_data = reactive({
  setIntervalFlag: null
})


const stopPolling = () => {
  // 清除定时器
  if (arocde_data.setIntervalFlag) {
    clearInterval(arocde_data.setIntervalFlag);
    arocde_data.setIntervalFlag = null;
  }
}

const startPolling = () => {
  // 设置轮询间隔时间，例如5秒
  const interval = 1000;
  // 使用setInterval发起请求
  arocde_data.setIntervalFlag = setInterval(() => {
    lunxun()
  }, interval);
}

const lunxun = async() => {
    const data = await getChatCategoryListspl({batch_key: batch_key.value,is_batch:1})
    plLists.value = data.list
}


const chatContentList = ref<any[]>([])
const chatLogParams = reactive({
  type: 2,
  category_id: sessionActive.value,
  page_type: 1,
  page_no: 1,
  page_size: 15
})
const hasMoreDialogueRecords = ref<boolean>(false)
const dialogueRecordsLoading = ref<boolean>(false)

/**
 * 1.上拉加载
 * 2.切换分类时重制上拉
 * 3.对话以后加载(最新一条就行)
 * flag = 1的时候表示对话结束了，获取最新一条数据
 **/
let contentListHeight = 0 // 旧记录高度，新记录高度 - 旧记录高度得到最新刷新定位位置
//获取聊天记录
const getChatList = async (flag?: boolean) => {
  dialogueRecordsLoading.value = true
  hasMoreDialogueRecords.value = true
  try {
    const chatElement = document.getElementsByClassName('contentList')[0]
    const data = await getchatLog({
      ...chatLogParams,
      page_no: flag ? 1 : chatLogParams.page_no,
      page_size: flag ? 1 : chatLogParams.page_size
    })
    const {page_no, page_size} = chatLogParams
    if (
        page_no * page_size > data.count ||
        chatContentList.value.length / 2 >= data.count
    ) {
      hasMoreDialogueRecords.value = false
    }

    const transformData = data.lists.map((item: any) => {
      if (item.type == 1) {
        return {...item, from_avatar: userStore.userInfo.avatar}
      } else {
        return {
          ...item,
          from_avatar: appStore.config.chat.chat_logo
        }
      }
    })

    if (flag) {
      chatContentList.value.splice(-2, 2)
      chatContentList.value = [...chatContentList.value, ...transformData]
    } else {
      chatContentList.value = [...transformData, ...chatContentList.value]
    }

    // 刷新记录时将滚动条定位到刷新之前的元素那里
    await nextTick()

    if (currentSession.value == '新的会话') {
      //  chatContentList.value = []
      //return
    }
    const rect = Object.freeze(chatElement?.getBoundingClientRect())
    console.log('高度')
    console.log(rect && contentListHeight)
    if (rect && contentListHeight) {
      chattingRef.value?.scrollTo(rect.height - contentListHeight)
    }
    contentListHeight = rect.height
  } catch (e) {
    console.log('聊天记录错误', e)
  } finally {
    dialogueRecordsLoading.value = false
  }
}

const handleTop = () => {
  if (hasMoreDialogueRecords.value && contentListHeight) {
    chatLogParams.page_no += 1
    getChatList()
  }
}
const is_add_none = ref(0)
const model_file = ref('')
const model_image = ref('')

const qingkong = () => {
  chatLogParams.category_id = -1
  sessionActive.value = -1
  chatContentList.value = []
  chatLogParams.page_no = 1
  getChatList()
}

const {pauseAll} = useAudioPlay()
const isReceiving = ref(false)
const newUserInput = ref<string>('')

const contentPostv1 = async (userInput: any, type = 1, str = '') => {
  if (!userStore.isLogin) return userStore.toggleShowLogin(true)
  if (isReceiving.value) return
  isReceiving.value = true
  is_submit.value = true
  sendDisabled.value = true
  if (userStore.userInfo.is_chat_limit && isNewDay(true, CHAT_LIMIT_KEY)) {
    try {
      await ElMessageBox.confirm(
          '已超过会员对话上限次数，继续对话将会消耗账户的对话余额',
          '对话上限提示',
          {
            showClose: false,
            confirmButtonText: '继续',
            cancelButtonText: '关闭'
          }
      )
    } catch (e) {
      isReceiving.value = false
      return
    }
  }

  //if(is_add_none.value == 0) {
   // is_add_none.value = 1
    if (type == 0 || sessionActive.value == -1) {
      await sessionAdd(2, currentId.value, 1)
    }
    if (sessionActive.value == -1 || currentSession.value === '新的会话') {
      await sessionEdit(sessionActive.value, str)
    }
 // }
  newUserInput.value = userInput


  // 缓存使用的插件id
  const pluginId = useCookie(PLUGIN_MODEL_KEY)
  pluginId.value = plugins.id
  console.log(userInput.img_understand)


  let mer_data = {
    question: userInput,
    type: 2,
    other_id: currentId.value,
    category_id: sessionActive.value,
    ...chatParams,
    model: plugins.id ? plugins.id : chatParams.model,
    transcription_url:is_videomp3.value==1?'':is_videomp3.value,
    video_understand_url:is_video.value==1?'':is_video.value,
    is_custom_dialogue: type,
    is_immediately: type == 0 ? 1 : 0,
    batch_key:batch_key.value
 }



// 正则仅匹配需要处理的前缀，后跟可选数字
const FIELD_REGEX = /^(form_up|file_up|img_understand|img_up|img_generation)\d*$/;
Object.keys(userInput).forEach(key => {
  if (FIELD_REGEX.test(key)) {
    const files = userInput[key];
    if (!Array.isArray(files)) return;

    // 根据前缀生成新键名
    let newKey;
    if (key.startsWith('img_understand')) {
      newKey = 'img_understand_url';
    } else if (key.startsWith('file_up')) {
      newKey = 'file_url';
    } else if (key.startsWith('form_up')) {
      newKey = 'form_url';
    } else if (key.startsWith('img_up')) {
      newKey = 'img_url';
    } else if (key.startsWith('img_generation')) {
      newKey = 'img_generation_url';
    } else {
      return; // 正则已确保不会执行到此处
    }

    // 处理文件数组并存入新键名
    mer_data[newKey] = files
      .map(item => {
        if (!item) return null;
        return item.cid !== undefined
          ? item.url
          : item.response?.data?.url ?? '';
      })
      .filter(url => url?.trim()) // 过滤空值
      .join(', '); // 转换为字符串
  }
});


  console.log(pl_none.value)
  // 处理所有需要删除的字段（包括基础字段名和带数字后缀的字段）
  Object.keys(userInput).forEach(key => {
    if (pl_none.value.some(prefix => key.startsWith(prefix))) {
      console.log(`删除 ${key}`)
      delete userInput[key];
    }
  });
  console.log('有数据吗22')
  console.log(userInput.img_up)

  let data = await chatSendTextv1(mer_data).catch((error) => {
    // 处理错误信息，兼容字符串和对象两种情况
    let errorMessage = '';
    if (typeof error === 'string') {
      errorMessage = error;
    } else if (error?.response?._data?.message) {
      errorMessage = error.response._data.message;
    } else if (error?.message) {
      errorMessage = error.message;
    } else {
      errorMessage = error?.toString() || '未知错误';
    }
    
    console.log('Error details:', {
      originalError: error,
      errorMessage: errorMessage
    });

    if(errorMessage == '使用了会员功能，请先开通会员~'){
       ElMessageBox.confirm(
           '会员专用功能，当前未开通会员',
           '对话提示',
           {
             showClose: false,
             confirmButtonText: '去开通',
             cancelButtonText: '关闭'
           }
       ).then(() => {
         // 用户点击确认，执行页面跳转
         router.push('/openvip');
       }).catch(() => {
         // 用户点击取消，执行其他逻辑（如果有需要）
         isReceiving.value = false
         sendDisabled.value = false
       });
     }
    if(errorMessage == '对话余额不足'){
      is_submit.value = false
      ElMessageBox.confirm(
          'T币不足',
          '提示',
          {
            confirmButtonText: '去充值',
            cancelButtonText: '暂不使用',
            type: 'warning',
          }
      ).then(() => {
        router.push('/openvip?mode=recharge');
      })
      .catch(() => {
        isReceiving.value = false
        sendDisabled.value = false
      })
    }

    if(errorMessage != '对话余额不足' && errorMessage != '使用了会员功能，请先开通会员~'){
      is_submit.value = false
      isReceiving.value = false
      sendDisabled.value = false
      //feedback.msgError(errorMessage)
    }

  });
  if(data) {
    let edsts = {
      type: 1,
      content: str,
      from_avatar: userStore.userInfo.avatar,
      file_url: plugins.file.url,
      file_name: plugins.file.name,
      file_type: plugins.type == '' ? 0 : plugins.type == 'image' ? 1 : 2
    }
    chatContentList.value.push(edsts)
    console.log(edsts)
    isReceiving.value = false
    sendDisabled.value = false
    for (let i = 0; i < pl_none.value.length; i++) {
      let key = pl_none.value[i]

      if (typeof (userInput[key]) != 'undefined') {
        if (typeof (userInput[key]) == 'number') {
          userInput[key] = '1'
        } else if (typeof (userInput[key]) == 'object') {
          userInput[key] = []
        } else {
          userInput[key] = ''
        }
      }
    }
    console.log(userInput)
    optionsLists.value = [];
    is_submit.value = false
    feedback.msgSuccess('成功！')
  }else{

  }
}


//发送问题
const contentPost = async (userInput: any, type = 1, str = '') => {
  if (!userStore.isLogin) return userStore.toggleShowLogin(true)
  if (isReceiving.value) return
  isReceiving.value = true
  sendDisabled.value = true
  if (userStore.userInfo.is_chat_limit && isNewDay(true, CHAT_LIMIT_KEY)) {
    try {
      await ElMessageBox.confirm(
          '已超过会员对话上限次数，继续对话将会消耗账户的对话余额',
          '对话上限提示',
          {
            showClose: false,
            confirmButtonText: '继续',
            cancelButtonText: '关闭'
          }
      )
    } catch (e) {
      isReceiving.value = false
      return
    }
  }

  //如果是视频解析





  if (type == 0 || sessionActive.value == -1) {
    await sessionAdd(2, currentId.value)
  }
  if (sessionActive.value == -1 || currentSession.value === '新的会话') {
    await sessionEdit(sessionActive.value, str)
  }
  newUserInput.value = userInput



  chatContentList.value.push({
    type: 1,
    content: str,
    from_avatar: userStore.userInfo.avatar,
    file_url: plugins.file.url,
    file_name: plugins.file.name,
    file_type: plugins.type == '' ? 0 : plugins.type == 'image' ? 1 : 2
  })
  const result = reactive({
    type: 2,
    loading: true,
    content: [],
    create_time: ' ',
    from_avatar: appStore.config.chat.chat_logo,
    id: ''
  })
  chatContentList.value.push(result)

  let file = ''
  let file1 = ''
  let file2 = ''
  let file3 = ''
  let file4 = ''
  let file5 = ''
  let file6 = ''
  // 缓存使用的插件id
  const pluginId = useCookie(PLUGIN_MODEL_KEY)
  pluginId.value = plugins.id
  console.log(userInput)
  console.log('执行了吗')



  let mer_data = {
    question: userInput,
    type: 2,
    other_id: currentId.value,
    category_id: sessionActive.value,
    ...chatParams,
    model: plugins.id ? plugins.id : chatParams.model,
    transcription_url:is_videomp3.value==1?'':is_videomp3.value,
    video_understand_url:is_video.value==1?'':is_video.value,
    is_custom_dialogue: type,
    is_immediately: type == 0 ? 1 : 0
 }



// 正则仅匹配需要处理的前缀，后跟可选数字
const FIELD_REGEX = /^(form_up|file_up|img_understand|img_up|img_generation)\d*$/;
Object.keys(userInput).forEach(key => {
  if (FIELD_REGEX.test(key)) {
    const files = userInput[key];
    if (!Array.isArray(files)) return;

    // 根据前缀生成新键名
    let newKey;
    if (key.startsWith('img_understand')) {
      newKey = 'img_understand_url';
    } else if (key.startsWith('file_up')) {
      newKey = 'file_url';
    } else if (key.startsWith('form_up')) {
      newKey = 'form_url';
    } else if (key.startsWith('img_up')) {
      newKey = 'img_url';
    } else if (key.startsWith('img_generation')) {
      newKey = 'img_generation_url';
    } else {
      return; // 正则已确保不会执行到此处
    }

    // 处理文件数组并存入新键名
    mer_data[newKey] = files
      .map(item => {
        if (!item) return null;
        return item.cid !== undefined
          ? item.url
          : item.response?.data?.url ?? '';
      })
      .filter(url => url?.trim()) // 过滤空值
      .join(', '); // 转换为字符串
  }
});






  delete userInput.file_up;
  delete userInput.img_up;
  delete userInput.form_up;
  delete userInput.img_understand;
  delete userInput.video_understand;
  delete userInput.transcription_up;
  delete userInput.img_generation;

  // 处理带数字后缀的字段删除
  Object.keys(userInput).forEach(key => {
    if (key.startsWith('file_up') || 
        key.startsWith('img_up') || 
        key.startsWith('form_up') || 
        key.startsWith('img_understand') || 
        key.startsWith('video_understand') || 
        key.startsWith('transcription_up') || 
        key.startsWith('img_generation')) {
      console.log(`删除 ${key}`)
      delete userInput[key];
    }
  });

  console.log(is_videomp3)
  try {
    await chatSendText(
      mer_data,
        {
          onstart(reader) {
            streamReader = reader
            pauseAll()
          },
          onmessage(value) {
            value
                .trim()
                .split('data:')
                .forEach(async (text) => {
                  if (text !== '') {
                    try {
                      const dataJson = JSON.parse(text)
                      const {
                        id: chatId,
                        code,
                        event,
                        data,
                        index,
                        incremental
                      } = dataJson
                      if(data == '您使用了会员功能，请先成为会员'){
                        dialogVisibleVip.value = true
                        await getChatList(true)
                        await nextTick()
                        chattingRef.value.scrollToBottom()
                        return false;
                      }
                      if (event == 'error' && code === 101) {
                        guidedPopupRef.value?.open()
                      } else if (event == 'error') {
                        feedback.msgError(data)
                        chattingRef.value.setInput(
                            newUserInput.value
                        )
                      }

                      if (data) {
                        if (!result.content[index]) {
                          result.content[index] = ''
                        }
                        result.content[index] = incremental
                            ? result.content[index] + data
                            : data
                      }
                      if (event === 'finish') {
                        result.loading = false

                        if (plugins.id == 'gpt-4-all') {
                          resetPluginData()
                        }
                        return
                      }
                    } catch (error) {
                    }
                  }
                })
          },
          onclose() {
            isReceiving.value = false
            sendDisabled.value = false
            //如果是星火就1分钟后在刷新


           if(chatModelConfig.value.key.includes('Spark')){
             setTimeout(async () => {
               await getChatList(true)
               await nextTick()
               chattingRef.value.scrollToBottom()
             }, 30000)
             userStore.getUser()
           }else{
             setTimeout(async () => {
               await getChatList(true)
               await nextTick()
               chattingRef.value.scrollToBottom()
             }, 800)
             userStore.getUser()
           }

          }
        }
    )
  } catch (error) {
    console.log(error)
    isReceiving.value = false
    sendDisabled.value = false
    chattingRef.value.setInput(newUserInput.value)
    chatContentList.value.splice(chatContentList.value.length - 2, 2)
  }

  nextTick(() => {
    chattingRef.value.scrollToBottom()
  })
}

let streamReader: ReadableStreamDefaultReader<Uint8Array> | null = null
const chatClose = (index?: number) => {

    streamReader?.cancel()
    if (index) {
      chatContentList.value[index].loading = false
    }
    isReceiving.value = false

}


watch(formData, async (v1) => {
    console.log('变化了')
    console.log(v1)
})

//清空会话
const cleanChatLog = async () => {
  await sessionAdd(2, currentId.value)
}



onMounted(async () => {
  if (route.query.cid || route.query.user_sn) {
    const cid: any = useCookie('cid')
    const user_sn: any = useCookie('user_sn')
    cid.value = route.query.cid
    user_sn.value = route.query.user_sn
    await nextTick()
    userStore.checkShare()
  }

  chatContentList.value = []
  sessionActive.value = cate_id.value>0?cate_id.value:-1
  chatLogParams.category_id = cate_id.value>0?cate_id.value:-1
  await getChatList()
  await nextTick()
  batch_key.value =  crypto.randomUUID();
  chattingRef.value.scrollToBottom()
})
watch(sessionActive, async (v1) => {
  // 切换对话重置分页数据 Start
  chatLogParams.category_id = v1
  chatLogParams.page_no = 1
  chatContentList.value = []
  contentListHeight = 0
  // 切换对话重置分页数据 End
  chatClose()
  ///await getChatList()
  await nextTick()
  chattingRef.value.scrollToBottom()
})

definePageMeta({
  layout: false
})
</script>
<style lang="scss" scoped>
.container-tip {
  border: 1px solid #fb9a3b;
}

.item {
  :hover {
    color: #fb9a3b;
  }
}

.back {
  position: absolute;
  top: 20px;
  background: white;
  padding: 5px;
  border-radius: 5px;
  color: #7c776e;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  z-index: 9999;
}
.chat-item[data-v-fc8ab866] {
  width: 100%;
  display: flex;
  max-width: 1280px;
}
.ai-avatar[data-v-fc8ab866] {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  overflow: hidden;
  margin-right: 13px;
}
.not-chat-content[data-v-fc8ab866] {
  width: 80%;
  background: rgba(250,251,255,.8);
  padding: 20px;
  box-sizing: border-box;
  border-radius: 8px;
}
.fill img[data-v-12bde410] {
  width: 100%;
  height: 100%;
}
.welcome-content[data-v-fc8ab866] {
  width: 100%;
}
.welcome-name[data-v-fc8ab866] {
  width: 100%;
  font-size: 22px;
  font-weight: 700;
  color: var(--gradient-1);
  margin-bottom: 16px;
}
.welcome-content[data-v-fc8ab866] {
  width: 100%;
}
.ai-chat-bottom-main {
  width: calc(100% - 45px);
  padding: 0 0 0 24px;
  box-sizing: border-box;
  position: fixed;
  bottom: 0;
  z-index: 3;
}
.ai-chat-header{
  width: 60%;
  height: 58px;
  padding: 0 20px 0 24px;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fafbff;
  box-shadow: 0 1px 5px 0 #dedede;
  position: absolute;
  top: 0;
  z-index: 5;
}
.ai-chat-header-left {
  max-width: calc(100% - 80px);
  display: flex;
  align-items: center;
}
.ai-avatar{
  width: 32px;
  height: 32px;
  min-width: 32px;
  min-height: 32px;
  border-radius: 8px;
  overflow: hidden;
  margin-right: 12px;
}
.fill img{
  width: 100%;
  height: 100%;
}
 .ai-name {
  font-size: 18px;
  font-weight: 700;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  margin-right: 8px;
}
.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}
.ai_free {
  color: #784c2c;
  background: #ffd700;
}
.ai_freev1 {
  color: #784c2c;
  background: #ebcd77;
}

.ai_useType{
  min-width: 62px;
  height: 22px;
  font-size: 12px;
  border-radius: 11px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.invite-btn {
  height: 22px;
  border-radius: 11px;
  background-color: #fb9803;
  padding: 0 8px;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #2b2727;
}

.invite-btnv1 {
  height: 22px;
  border-radius: 11px;
  background-color: #fcd8bd;
  color: #784c2c;
  padding: 0 8px;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
}

.ic_coin{
  width: 14px;
  height: 14px;
  min-width: 14px;
  min-height: 14px;
  margin-right: 4px;
}
.pos {
  position: absolute;
  right: -2px;
  top: -5px;
  width: 26px!important;
  height: 16px!important;
}
</style>
